﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;
using dooll.Common;
namespace dooll.Passport
{

    public partial class WebLogin : System.Web.UI.Page
    {
       
        private dooll.Config.AppConfigInfo XCAC = dooll.Config.AppConfig.load();
        bool bIsAjax = false;
        string sSaveState = "0";
        protected void Page_Load(object sender, EventArgs e)
        {
            string sUserName = Request.Form["txtUserName"];             //用户名
            string sPassWord = Request.Form["txtPassword"];             //密码
            string sValidCode = Request.Form["textValidCode"];          //填写的验证码
            string sToken = Request.Form["token"];                      //通行证令牌
            string sReturnUrl = Request.Form["toUrl"];                  //登录成功转向
 
            string sIsAjax = Request.Form["IsAjax"];                    // 是否AJAX
            bIsAjax = (string.IsNullOrEmpty(sIsAjax) || (sIsAjax != "1")) ? false : true; //是否AJAX
            

            if (!(string.IsNullOrEmpty(sUserName) && string.IsNullOrEmpty(sPassWord)))
            {

                #region 验证码处理
                //if (sValidCode != null && sValidCode.Length == 4)
                //{
                //    if (Request.Cookies["CheckCode"] == null)
                //    {
                //        Response.Write(jsAlert(500,"浏览器不支持Cookie或是未生成验证码!", 1, null));
                //        Response.End();
                //    }
                //    string strCode = Request.Cookies["CheckCode"].Value;
                //    if (string.IsNullOrEmpty(strCode) || sValidCode != strCode)
                //    {
                //        Response.Write(jsAlert(403,"提示:请输入正确的验证码!", 1, null));
                //        Response.End();
                //    }
                //}
                //else
                //{
                //    Response.Write(jsAlert(403,"提示:请输入正确的验证码!", 1, null));
                //    Response.End();
                //}
                #endregion

                sUserName = sUserName.Trim();

                if (string.IsNullOrEmpty(sUserName) || sUserName.Length < 1)
                {
                    Response.Write(jsAlert(403,"提示:请输入正确的用户名（至少1位）!", 1, null));
                    Response.End();
                }

                if (string.IsNullOrEmpty(sPassWord) && sPassWord.Length < 3 && string.IsNullOrEmpty(sToken))
                {
                    Response.Write(jsAlert(403,"提示:请输入正确的密码（至少三位）!", 1, null));
                    Response.End();
                }
                doLogin(sUserName, sPassWord, sReturnUrl, sToken);
            }

        }
        protected int doLogin(string sUserName, string sPassWord, string sReturnUrl, string token)
        {
            dooll.Common.PassportInfo Pa = new dooll.Common.PassportInfo();
            int iStaus;
            try
            {
                string strIp = Request.ServerVariables["remote_addr"];
                PassportManage pm = new PassportManage("default");
                iStaus = pm.Login(sUserName, sPassWord, strIp, SessionID(), ref Pa, token);

                if (Pa != null)
                {
                
                    switch (iStaus) //错误代码
                    {

                        case 0:
                            #region 登录成功

                            //产生令牌
                            string tokenValue = Pa.Token;

                            //tokenCookie.Domain = "passport.com";
                            //Response.AppendCookie(tokenCookie);

                            //产生主站凭证
                            //object info = true;

                            string PaValue = Newtonsoft.Json.JavaScriptConvert.SerializeObject(Pa);

                            int timeout = (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["timeout"])) ? 20 : int.Parse(System.Configuration.ConfigurationManager.AppSettings["timeout"]);

                            CacheManager cm = new CacheManager();
                            if (!cm.TokenInsert(tokenValue, PaValue, timeout, Request.ServerVariables["HTTP_REFERER"], strIp, sUserName, Pa.UserID, Pa.Mode))
                            {
                                /*无法写入数据库操作*/
                                Response.Write(jsAlert(500, cm.ErrInfo, 1, null));
                                return iStaus;
                            }
                            else
                            {
                                /*写入Cookie令牌*/
                                //string tokenValue = this.getGuidString();
                                HttpCookie tokenCookie = new HttpCookie(XCAC.PassportTokenCookie);
                                tokenCookie.Values.Add("Value", tokenValue);
                                if (!string.IsNullOrEmpty(sSaveState) && sSaveState == "1")
                                    tokenCookie.Expires = DateTime.Now.AddDays(30); //设定过期时间
                                Response.AppendCookie(tokenCookie);
                            }
                            cm.Dispose();
                            cm = null;

                            //带主站令牌跳转回分站
                            if (!string.IsNullOrEmpty(sReturnUrl))
                            {
                                if (!sReturnUrl.ToLower().StartsWith("javascript:"))
                                {
                                    Response.Redirect(getTokenURL(sReturnUrl, tokenValue));
                                }
                                else
                                {
                                    Response.Write(jsAlert(1, "你已经登录成功！", 1, sReturnUrl.Replace("javascript:", "")));
                                }

                            }
                            else if (string.IsNullOrEmpty(Request.ServerVariables["HTTP_REFERER"]) || Request.ServerVariables["HTTP_REFERER"] == Request.Url.AbsoluteUri)
                            {
                                Response.Write(jsAlert(1, "你已经登录成功！", 1, null));
                            }
                            else
                            {
                                Response.Redirect(getTokenURL(Request.ServerVariables["HTTP_REFERER"], tokenValue));
                            }

                            #endregion 

                            return iStaus;
                        default : //其他情况
                            Response.Write(jsAlert(iStaus, pm.ErrMessage, 1, null));
                            return iStaus;
                            
                    }
                }
                else
                {
                    Response.Write(jsAlert(500, pm.ErrMessage, 1, null));
                    return 500;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                return 500;
            }

        }
        public string SessionID()
        {
            string SessionCookieName = "_dooll_SessionId_";  
            if (Request.Cookies[SessionCookieName]==null||string.IsNullOrEmpty(Request.Cookies[SessionCookieName].Value))
            {
                HttpCookie cookieSession = new HttpCookie(SessionCookieName, Session.SessionID);
                Response.AppendCookie(cookieSession);
            }
            return Request.Cookies[SessionCookieName].Value;
        }

        /// <summary>
        /// 产生绝对唯一字符串，用于令牌
        /// </summary>
        /// <returns></returns>
        private string getGuidString()
        {
            return Guid.NewGuid().ToString().ToLower();
        }

        public void Alert(string strAlert, int type, string GoPage)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "提示", jsAlert(strAlert, type, GoPage));
        }

        public void Alert(string strAlert)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "提示", jsAlert(strAlert, 0, null));
        }

        #region javascript 提示功能
        /// <summary>
        /// javascript 提示功能
        /// </summary>
        /// <param name="strAlert">提示内容</param>
        /// <param name="type">0不操作,1退回 ,2转向页面,3关闭窗口,4刷新父级窗口关闭子窗口</param>
        /// <param name="GoPage">type=2 的转向页面</param>
        /// <returns>javascript 提示构成的字符串</returns>
        private string jsAlert(int State,string strAlert, int type, string GoPage)
        {
            if (bIsAjax)
            {
                //return string.Concat(State, ",", strAlert);
                return jsAlert(strAlert, 0, GoPage);
            }
            else
            {
                return jsAlert(strAlert, type, GoPage);
            }
        }
        private string jsAlert(string strAlert, int type, string GoPage)
        {
            string temp;
            temp = "<script type='text/javascript'>";
            temp += "alert('" + strAlert + "');";
            switch (type)
            {
                case 0:
                    break;
                case 1:
                    temp += "history.back();";
                    break;
                case 2:
                    temp += "location.href='" + GoPage + "';";
                    break;
                case 3:
                    temp += "window.close();";
                    break;
                case 4:
                    temp += "window.opener.location.reload();";
                    temp += "window.close();";
                    break;
                default:
                    temp += "";
                    break;
            }
            temp += "</script>";
            return temp;
        }
        #endregion

        /// <summary>
        /// 获取带令牌请求的URL
        /// 在当前URL中附加上令牌请求参数
        /// </summary>
        /// <returns></returns>
        
        private string getTokenURL()
        {
            string url = Request.Url.AbsoluteUri;
            Regex reg = new Regex(@"^.*\?.+=.+$");
            if (reg.IsMatch(url))
                url += "&Token=$Token$";
            else
                url += "?Token=$Token$";

            return string.Concat(XCAC.PassportGetTokenPage, "?", "toUrl=" + Server.UrlEncode(url));
        }

        /// <summary>
        /// 获取带令牌请求的URL
        /// 在当前URL中附加上令牌请求参数
        /// </summary>
        /// <returns></returns>
        private string getTokenURL(string toUrl,string TokenValue)
        {
            //Uri u = new Uri(toUrl);

            //String[] q = u.Query.Split(Convert.ToChar("&"));

            //String s= "?" ;

            //for (var i = 0; i < q.Length-1; i++)
            //{
            //    String[] qi = q[i].Split(Convert.ToChar("&"));
            //    s = String.Concat(s, qi[0], "=", (qi[0].ToLower() == "token") ? TokenValue : qi[1], "&");
            //}

            //return s.Substring(1);

            if (toUrl.EndsWith("?"))
            {
                toUrl = toUrl.Substring(0, toUrl.Length - 1);
            }

            toUrl = Regex.Replace(toUrl, @"(\?|&)Token=.*", "", RegexOptions.IgnoreCase);
            string sSessionId = Request.Form["SessionId"];
            Regex reg = new Regex(@"^.*\?.+=.+$");
            if (reg.IsMatch(toUrl))
                toUrl += string.Concat("&Token=", TokenValue);
            else
                toUrl += string.Concat("?Token=", TokenValue);
            return toUrl;
        }
    }
}